<template>
  <div>
    <h1>分类维护</h1>
    <el-switch
      v-model="draggable"
      active-color="#13ce66"
      inactive-color="#ff4949"
    >
    </el-switch
    >开启拖拽
    <el-tree
      :draggable="draggable"
      @node-drop="nodeDrop"
      :allow-drop="allowDrop"
      node-key="catId"
      :default-expanded-keys="ids"
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            update
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog title="分类编辑" :visible.sync="dialogFormVisible">
      {{ category }}
      <el-form :model="category">
        <el-form-item label="分类名称" :label-width="formLabelWidth">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      draggable: false,
      updateNodes: [],
      pid: 0,
      levle: 1,
      catLevel: 1,
      ids: [],
      data: [],
      category: {
        name: "",
        sort: 0,
        showStatus: 1,
      },
      formLabelWidth: "120px",
      dialogFormVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },

  activated() {
    this.getDataList();
  },
  methods: {
    //和数据库交互，同步数据
    /**
     * draggingNode:被拖拽的对象,
     * dropNode:目标对象,
     * type:拖拽类型：after before inner
     */
    nodeDrop(draggingNode, dropNode, type) {
      //console.log(draggingNode, dropNode, type);
      if (type == "before" || type == "after") {
        this.pid = dropNode.data.parentCid;

        let flag = false;
        let updateCildrenNode = null;
        if (draggingNode.data.catLevel != dropNode.data.catLevel) {
          this.level = dropNode.data.catLevel;
          flag = true;
          updateCildrenNode = draggingNode;
        }

        //收集
        if (this.pid == 0) {
          this.getUpdateNodes(dropNode.parent.data, flag, updateCildrenNode);
        } else {
          this.getUpdateNodes(
            dropNode.parent.data.children,
            flag,
            updateCildrenNode
          );
        }
      } else if (type == "inner") {
        this.pid = dropNode.data.catId;
        this.level = dropNode.data.catLevel + 1;
        //收集数据
        this.getUpdateNodes(dropNode.data.children, false, null);
      }
      //查看收集之后的结果
      console.log("被收集的数据", this.updateNodes);

      this.$http({
        url: this.$http.adornUrl(`/product/category/updateNodes`),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        console.log(data);
        if (data && data.code == 0) {
          this.$message({
            message: "拖拽成功",
            type: "success",
          });
          this.updateNodes = [];
          this.getDataList();
        }
      });
    },
    //收集后台需要的元素，还需要一个参数，表示：是否需要收集子元素
    //node是被拖拽对象
    getUpdateNodes(nodes, flag, node, level = this.level, pid = this.pid) {
      console.log("需要被收集的元素是", nodes);
      console.log("被拖拽的对象", node);
      for (var i = 0; i < nodes.length; i++) {
        this.updateNodes.push({
          catId: nodes[i].catId,
          name: nodes[i].name,
          parentCid: pid,
          catLevel: level,
          sort: i,
        });
      }
      if (flag) {
        if (node != null) {
          console.log(level);
          this.getUpdateNodes(
            node.childNodes,
            false,
            null,
            level + 1,
            node.data.catId
          );
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type);
      //计算被拖拽的对象层数
      this.getCountLevel(draggingNode);
      if (type == "next" || type == "prev") {
        if (this.catLevel == 1) return true;
        if (this.catLevel == 2 && dropNode.data.catLevel != 3) return true;
        if (this.catLevel == 3 && dropNode.data.catLevel == 1) return true;
      } else {
        if (this.catLevel == 1 && dropNode.data.catLevel != 3) return true;
        if (this.catLevel == 2 && dropNode.data.catLevel == 1) return true;
      }
      return false;
    },
    getCountLevel(node) {
      //node是被拖拽的对象
      this.catLevel = 1;
      if (node.childNodes.length > 0) {
        this.catLevel = 2;
        for (var i in node.childNodes) {
          if (node.childNodes[i].childNodes.length > 0) {
            this.catLevel = 3;
            return;
          }
        }
      }
    },
    remove(node, data) {
      console.log(node, data);
      let delIds = [node.data.catId];
      this.$http({
        url: this.$http.adornUrl(`/product/category/delete`),
        method: "post",
        data: this.$http.adornData(delIds, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            onClose: () => {
              this.dialogFormVisible = false;
              this.getDataList();
              this.ids[0] = node.data.parentCid;
            },
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    update(node) {
      this.dialogFormVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${node.catId}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.category = data.category;
      });
    },
    save() {
      let methodUrl = "save";
      if (this.category.catId) {
        methodUrl = "update";
      }
      this.$http({
        url: this.$http.adornUrl(`/product/category/${methodUrl}`),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code == 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            onClose: () => {
              this.dialogFormVisible = false;
              this.getDataList;
              this.ids[0] = this.category.parentCid;
              this.category = {
                sort: 0,
                showStatus: 1,
              };
            },
          });
        }
      });
    },

    append(node) {
      console.log("被点击的元素", node);
      this.dialogFormVisible = true;
      this.category.parentCid = node.catId;
      this.category.catLevel = node.catLevel + 1;
      // this.category.showStatus = node.showStatus;
    },
    handleNodeClick(node) {
      console.log(node);
    },
    // 获取数据列表
    getDataList() {
      this.$http({
        url: this.$http.adornUrl("/product/category/tree/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        //console.log(data);
        this.data = data.list;
      });
    },
  },
  created() {
    this.getDataList();
  },
};
</script>
